<?php
/**
 *	description:ZMAXWECHAT material类实现文件
 *  author：min.zhang
 *  Email:zhang19min88@163.com
 *	Url:http://www.zmax99.com
 *  copyright:南宁市程序人软件科技有限责任公司保留所有权利
 *  date:2016-04-29
 *  @license GNU General Public License version 3, or later
 */
 
defined('_JEXEC') or die('Restricted access');

class zmaxwechatMaterial
{
	protected $addImageToServerUrl='https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=';	
	protected $getMaterialUrl='https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=';
	public function __construct($token)
	{
		$this->addImageToServerUrl = $this->addImageToServerUrl.$token."&type=image";
		$this->getMaterialUrl = $this->getMaterialUrl.$token;
	}
	
	//得到资源的信息
	public function getMediaInfo($fileFullPath)
	{
		$md5 =md5_file($fileFullPath);
		$result = $this->testUploaded($md5);
		if($result)
		{
			return $result->info;
		}
		else
		{
			$info = $this->addImageToServer($fileFullPath);
			$newMaterial = new stdClass();
			$newMaterial->md5= $md5;
			$newMaterial->path = substr($fileFullPath ,strlen(JPATH_ROOT.DS));
			$newMaterial->info = $info;
			$db = JFactory::getDBO();
			$db->insertObject("#__zmaxwechat_material",$newMaterial);
			return $info;
		}
		
	}
	
	public function testUploaded($md5Value)
	{
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select("*")->from("#__zmaxwechat_material")->where("md5='".$md5Value."'");
		$db->setQuery($query);
		$result = $db->loadObject();
		return $result;
	}
	
	//向服务器增加永久素材
	public function addImageToServer($file)
	{
		$params['media']  = '@'.$file;  
        $result=$this->http_post_media($this->addImageToServerUrl, $params);
		return $result;
	}
	
	//向服务器获得永久素材
	
	


	
	public function  http_post_media($url,$strPOST)  
	{
		$oCurl = curl_init ();  
        if (stripos ( $url, "https://" ) !== FALSE)
		{  
            curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE );  
            curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, false );  
        }  
  
        curl_setopt ( $oCurl, CURLOPT_URL, $url );  
        curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, 1 );  
        curl_setopt ( $oCurl, CURLOPT_POST, true );  
        curl_setopt ( $oCurl, CURLOPT_POSTFIELDS, $strPOST );  
        $sContent = curl_exec ( $oCurl );  
        $aStatus = curl_getinfo ( $oCurl );  
        curl_close ( $oCurl );  
        if (intval ( $aStatus ["http_code"] ) == 200) 
		{  
            return $sContent;  
        } 
		else 
		{  
            return false;  
        }  
	}
	
}


